package com.wwinsoft.framework.dao.system;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import com.wwinsoft.framework.entity.system.Code;
import com.wwinsoft.modules.orm.hibernate.HibernateDao;

@Repository
@SuppressWarnings("unchecked")
public class CodeDao extends HibernateDao<Code, Long> {

    public Code getCodeByTypeAndCodeValue(String codeType, String codeValue) {
        Query query = this.createQuery("from Code c where c.codeType.typeCode = ? and c.value = ?", codeType,
                                       codeValue);
        query.setCacheable(true);
        return (Code) query.uniqueResult();
    }


    public List<Code> getCodeListByType(String codeType) {
        Query query = this.createQuery("from Code c where c.codeType.typeCode=? order by c.id", codeType);
        query.setCacheable(true);
        return query.list();
    }

    public List<Code> getCodeListByTable(String table, String codeColumn, String valueColumn, String where) {
        StringBuilder sb = new StringBuilder();
        sb.append("select distinct ").append(castString(codeColumn)).append(" as code,").append(castString(valueColumn)).append(" as value");
        sb.append(" from ").append(table);
         if(StringUtils.isNotEmpty(where)){
             sb.append(" where ").append(where);
         }
        Query query = this.getSession().createSQLQuery(sb.toString()).addScalar("code").addScalar("value")
                .setResultTransformer(Transformers.aliasToBean(Code.class));
        return query.list();
    }

    public Code getCodeByTable(String table, String codeColumn, String valueColumn, String where, String codeValue) {
        StringBuilder sb = new StringBuilder();
        sb.append("select distinct ").append(castString(codeColumn)).append(" as code,").append(castString(valueColumn)).append(" as value");
        sb.append(" from ").append(table);
        sb.append(" where ").append(valueColumn).append(" = ").append(codeValue);
         if(StringUtils.isNotEmpty(where)){
             sb.append(" and").append(where);
         }
        Query query = this.getSession().createSQLQuery(sb.toString()).addScalar("code").addScalar("value")
                .setResultTransformer(Transformers.aliasToBean(Code.class));
        return (Code)query.uniqueResult();
    }

    private String castString(String column){
        return new StringBuilder().append("cast(").append(column).append(" as char)").toString();
    }


}